import { ref } from 'vue'
import { defineStore } from 'pinia'

import TabBarManager from '../../utils/tabbar-manager'
//导入类型
import { USER_TYPES, TABBAR_CONFIG } from '../../types/user-types'
import { Businessman } from '../../types/login'
//导入服务
import {getuserlofo} from '../../services/login'
export const loginlofo = defineStore(
  'loginlofo1',
  () => {
  //  const userInfo=ref()
  //用户信息
  const userInfo = ref<Businessman>()
  
  // const InitialPath=ref<string>()
   //初始化用户信息和tabBar权限检测
   const initUserInfo= async ()=> {
      try {
        // 获取用户信息
        const res =await getuserlofo()
        console.log('用户信息',res)               
        userInfo.value=res.data.businessman
        
        // 保存用户信息
        // uni.setStorageSync('userInfo', userInfo)
        
        // 初始化 tabBar权限检测
        await TabBarManager.init(userInfo.value.department)
        
        console.log('✅ 用户信息和 TabBar 初始化完成', userInfo.value.department)
        
      } catch (error) {
        console.error('❌ 初始化用户信息失败:', error)
        goToLogin()
      }
    }
    //回到登录页面的方法
    const goToLogin = () => {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }
    //返回用户所有权限
    const getUsertype = () => {
      if(userInfo.value.department){
       return TABBAR_CONFIG[userInfo.value.department]
      }
      return []
    }
    //
    //删除用户
    const clearuserInfo = () => {
      userInfo.value = undefined
    }
    
    //记得 return
    return {
      
      userInfo,
      initUserInfo,
      goToLogin,
      getUsertype,
      clearuserInfo
    }
  },
  {
    // 持久化 - 使用 uni-app 兼容的存储方式
    persist: {
      storage: {
        setItem: (key: string, value: string): void => {
          uni.setStorageSync(key, value)
        },
        getItem: (key: string): string | null => {
          const item = uni.getStorageSync(key)
          return item === '' ? null : item
        }
      }
    },
  }
)